package com.littlebee.storychild.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.littlebee.storychild.R;
import com.littlebee.storychild.common.BaseApplication;
import com.littlebee.storychild.common.tcp.SendCmdBean;
import com.littlebee.storychild.common.tcp.TcpClientUtil;
import com.littlebee.storychild.common.utils.BabyStoryPlanEntry;
import com.littlebee.storychild.common.utils.CommonUtils;
import com.littlebee.storychild.common.utils.Constant;
import com.littlebee.storychild.common.utils.DateUtils;
import com.littlebee.storychild.common.utils.GsonUtils;
import com.littlebee.storychild.common.utils.LogUtil;
import com.littlebee.storychild.common.utils.NetWorkUtils;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.utils.Utils;
import com.littlebee.storychild.common.widget.CircleImageView;
import com.littlebee.storychild.common.widget.MyGridView;
import com.littlebee.storychild.common.widget.RoundAngleImageView;
import com.littlebee.storychild.ui.entry.Cartoons;
import com.littlebee.storychild.ui.entry.StorysEntry;
import com.littlebee.storychild.ui.entry.User;
import com.tjstudy.tcplib.ResponseCallback;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.fragment.BaseFragment;
import com.zss.library.utils.LogUtils;
import com.zss.library.widget.CommonWhiteDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.OnClick;

/*fragment页面*/

public class TestFragment extends BaseFragment implements View.OnClickListener {
    private static final String LAST_TIME = "last_time";
    private GridView gv, gv1, gv2;
    private CommonAdapter<StorysEntry> adapterStorysEntry;
    List<StorysEntry> nameStorysEntrys = new ArrayList<StorysEntry>();

    List<Cartoons> namesCartoons = new ArrayList<Cartoons>();
    private CommonAdapter<Cartoons> mAdapterCartoons;
    private CommonAdapter<BabyStoryPlanEntry> mAdapterBabyStoryPlanEntry;
    List<BabyStoryPlanEntry> namesBabyStoryPlanEntry = new ArrayList<BabyStoryPlanEntry>();

    private MediaPlayer mp = new MediaPlayer();
    int defaultIndex = -1;
    User user;
    SharedPreferences sharedPreferences;
    private RoundAngleImageView iv_4;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_test;
    }

    private static final int REFRESH_COMPLETE = 0X110;
    private static final int REFRESH_COMPLETE1 = 0X111;
   // boolean REFRESH_COMPLETE_OK = false, REFRESH_COMPLETE1_OK = false;
    JSONObject objectREFRESH_COMPLETE, objectREFRESH_COMPLETE1;
    long times;

    @Override
    public void initView() {
        sharedPreferences = getActivity().getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据
        setBackgroundResource(R.mipmap.boby_bg);
        user = Utils.getUserEntry();
        super.initView();
        gv = (GridView) findViewById(R.id.gv);
        gv1 = (GridView) findViewById(R.id.gv1);
        gv2 = (GridView) findViewById(R.id.gv2);
        iv_4 = (RoundAngleImageView) findViewById(R.id.iv_4);
        iv_4.setOnClickListener(this);

        TcpClientUtil.getInstance(getActivity()).sendMessage(SendCmdBean.CMD_BABY_CONNECT_TYPE);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        // TODO: 2017/8/28  今日故事
        adapterStorysEntry = new CommonAdapter<StorysEntry>(getActivity(), R.layout.layout_item_story) {
            @Override
            protected void convert(ViewHolder viewHolder, final StorysEntry workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                RoundAngleImageView iv = viewHolder.findViewById(R.id.photo);
                CircleImageView iv1 = viewHolder.findViewById(R.id.photo_1);
                //iv1.setVisibility(View.VISIBLE);
                name.setText(workerListEntry.getStoryid());
                // TODO: 2017/8/15
                Glide.with(getActivity()).load(workerListEntry.getStoryminiphoto()).error(R.mipmap.logo_img).into(iv);
                if (defaultIndex == i && mp.isPlaying()) {
                    iv1.setImageResource(R.mipmap.pause_hot);
                } else {
                    iv1.setImageResource(R.mipmap.play_normal);

                }

            }
        };
        gv.setAdapter(adapterStorysEntry);
        adapterStorysEntry.addAll(nameStorysEntrys);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (CommonUtils.isFast2Click())
                    return;
                FirstMotherDialog dialog = new FirstMotherDialog(getActivity(),
                        nameStorysEntrys.get(position), 2);
                dialog.show();
            }
        });
        //英语动画片
        mAdapterCartoons = new CommonAdapter<Cartoons>(getActivity(), R.layout.layout_item_story) {
            @Override
            protected void convert(ViewHolder viewHolder, final Cartoons workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                RoundAngleImageView iv = viewHolder.findViewById(R.id.photo);

                name.setText(workerListEntry.getCartoonname());
                // TODO: 2017/8/15
                Glide.with(getActivity()).load(workerListEntry.getCartoonminiphoto()).error(R.mipmap.logo_img).into(iv);


            }
        };
        gv2.setAdapter(mAdapterCartoons);
        mAdapterCartoons.addAll(namesCartoons);
        gv2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (CommonUtils.isFast2Click())
                    return;
                BaseApplication.getInstance().sendReportEvent("visitcartoon", namesCartoons.get(position).getCartoonid());
                FirstMotherDialog dialog = new FirstMotherDialog(getActivity(),
                        namesCartoons.get(position), 1);
                dialog.show();
            }
        });
        //宝宝想听故事
        mAdapterBabyStoryPlanEntry = new CommonAdapter<BabyStoryPlanEntry>(getActivity(), R.layout.layout_item_story) {
            @Override
            protected void convert(ViewHolder viewHolder, final BabyStoryPlanEntry workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                RoundAngleImageView iv = viewHolder.findViewById(R.id.photo);

                name.setText(workerListEntry.getStoryname());
                // TODO: 2017/8/15
                Glide.with(getActivity()).load(workerListEntry.getStoryminiphoto()).error(R.mipmap.logo_img).into(iv);


            }
        };
        gv1.setAdapter(mAdapterBabyStoryPlanEntry);
        mAdapterBabyStoryPlanEntry.addAll(namesBabyStoryPlanEntry);
        gv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO: 2017/8/28
                FirstMotherDialog dialog = new FirstMotherDialog(getActivity(),
                        namesBabyStoryPlanEntry.get(position), 0);
                dialog.show();
            }
        });

        onRefresh(false);
    }


    /**
     * 获取首页数据
     */
    protected void bindRefreshData() {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("deviceid", user.getMobile());
        times = System.currentTimeMillis();
        if (sharedPreferences.getString(LAST_TIME, "").equals("")) {
            hashMap.put("startdate", DateUtils.getTimeDay1(times));
        } else {
            hashMap.put("startdate", sharedPreferences.getString(LAST_TIME, ""));
        }
        hashMap.put("enddate", DateUtils.getTimeDay1(times));
        NetWorkUtils.post(getActivity(), "getsendtobaby", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                objectREFRESH_COMPLETE = resObj;
                mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 0);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);
                ToastUtil.displayShortToast("获取发送给宝宝的数据失败，请检查网络");
            }
        });
    }

    /**
     * 获取首页数据
     * TODO 没有正式数据
     */
    protected void getToday() {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("deviceid", user.getMobile());
        NetWorkUtils.post(getActivity(), "getstoryforbaby", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                objectREFRESH_COMPLETE1 = resObj;
                mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE1, 0);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);
                ToastUtil.displayShortToast("获取首页的数据失败，请检查网络");
            }
        });
    }


    /**
     * 上传宝宝选择的数据
     * TODO 没有正式数据
     */
    protected void sendToday(BabyStoryPlanEntry entry) {
        Map<String, String> hashMap = new HashMap<>();
        // {"result":{"rc":0,"rd":"getsendtobaby ok"},"response":{"cartoons":[],"storys":[]}}

        hashMap.put("deviceid", user.getMobile());
        hashMap.put("wantstoryid", entry.getStoryid());
        hashMap.put("wantaudiomsgurl", "http://47.92.37.125:9090/piecefile/18611697983-20170831102605.mp3");
        LogUtils.i("XHX", "ID:HB60000000" + ";wantstoryid:" + entry.getStoryid() + ";wantaudiomsgurl:" + "http://47.92.37.125:9090/piecefile/18611697983-20170831102605.mp3");
        NetWorkUtils.post(getActivity(), "setbabywantstory", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils
                        .i("XHX", "XHXERROR:" + result);


            }
        });
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
    }

    @Override
    public void onPause() {
        if (mp != null) {
            try {
                if (mp.isPlaying()) {
                    mp.release();
                    mp.stop();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            mp = new MediaPlayer();
        }
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_4:
                if (Utils.isLogin()) {
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    public void onRefresh(boolean isSuperView) {
        if (user != null && !TextUtils.isEmpty(user.getMobile())) {
            bindRefreshData();
            getToday();
        } else {
            if (isSuperView == true) {
                return;
            }
            ToastUtil.displayShortToast("请重新绑定串号");
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_COMPLETE:
                    // TODO: 2017/8/15
                    try {
                        sharedPreferences.edit().putString(LAST_TIME, DateUtils.getTimeDay1(times)).commit();
                        String res = objectREFRESH_COMPLETE.getJSONObject("response").optString("cartoons");
                        namesCartoons = GsonUtils.getListFromJSON(res, Cartoons.class);
                        //namesCartoons=namesCartoons.subList(0,2);
                        if (namesCartoons.size() == 1) {
                            gv2.setNumColumns(1);
                        } else if (namesCartoons.size() == 2) {
                            gv2.setNumColumns(2);
                        } else {
                            gv2.setNumColumns(3);
                        }
                        mAdapterCartoons.replaceAll(namesCartoons);
                        String res1 = objectREFRESH_COMPLETE.getJSONObject("response").optString("storys");
                        nameStorysEntrys = GsonUtils.getListFromJSON(res1, StorysEntry.class);
                        //nameStorysEntrys=nameStorysEntrys.subList(0,1);
                        if (nameStorysEntrys.size() == 1) {
                            gv.setNumColumns(1);
                        } else if (nameStorysEntrys.size() == 2) {
                            gv.setNumColumns(2);
                        } else {
                            gv.setNumColumns(3);
                        }

                        adapterStorysEntry.replaceAll(nameStorysEntrys);

                        LogUtils.i("XHX", "XHX故事大小:" + nameStorysEntrys.size());

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case REFRESH_COMPLETE1:
                    String res = objectREFRESH_COMPLETE1.optString("response");
                    namesBabyStoryPlanEntry = GsonUtils.getListFromJSON(res, BabyStoryPlanEntry.class);
                    LogUtils.i("XHX", "XHXSIZE:" + namesBabyStoryPlanEntry.size());
                    if (namesBabyStoryPlanEntry.size() == 1) {
                        gv1.setNumColumns(1);
                    } else if (namesBabyStoryPlanEntry.size() == 2) {
                        gv1.setNumColumns(2);
                    } else {
                        gv1.setNumColumns(3);
                    }
                    mAdapterBabyStoryPlanEntry.replaceAll(namesBabyStoryPlanEntry);
                    break;

            }
        }

    };


}
